<template>
  <div>
    <div class="mb-16">
      <el-button type="primary" @click="addProjectHandle">新增</el-button>
    </div>
    <el-table :data="tableData" stripe border height="calc(100vh - 150px)">
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="projectName" label="项目名称" />
      <el-table-column prop="localPath" label="本地路径" />
      <el-table-column prop="serve" label="服务器" :formatter="formatterServerData" />
      <el-table-column prop="remotePath" label="远程路径" />
      <el-table-column prop="sort" label="排序" sortable width="80" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button :icon="CopyDocument" circle @click="handleCopy(row, 'projectName')" />
          <el-button :icon="Edit" circle @click="handleEdit(row)" />
          <DownloadDirBtn :row="row" :serverConfigs="serverConfigs" />
          <el-button type="danger" :icon="Delete" circle @click="handleDelete(row)" />
        </template>
      </el-table-column>
      <el-table-column label="部署" type="expand" width="80">
        <template #default="{ row }">
          <DeployHandle :row="row" :serverConfigs="serverConfigs" />
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form ref="formDataRef" :model="formData" :rules="formDataRules" label-width="80px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="部署类型" prop="uploadType">
          <el-radio-group v-model="formData.uploadType">
            <el-radio :value="1">GZ压缩包</el-radio>
            <el-radio :value="2">文件</el-radio>
            <el-radio :value="3">目录</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="本地路径" prop="localPath">
          <el-input v-model="formData.localPath" placeholder="请输入本地路径">
            <template #append>
              <el-button :icon="Search" @click="selectFileHandle" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="服务器" prop="serve">
          <el-select v-model="formData.serve" filterable placeholder="请选择服务器">
            <el-option v-for="item in serverConfigs" :key="item.id" :label="`${item.name}-${item.id}`"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="远程路径" prop="remotePath">
          <el-input v-model="formData.remotePath" placeholder="请输入远程路径" />
        </el-form-item>
        <el-form-item label="备份方式" prop="backupMethod">
          <el-radio-group v-model="formData.backupMethod">
            <el-radio :value="1">远程</el-radio>
            <el-radio :value="2">本地</el-radio>
            <el-radio :value="3">不用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="版本">
          <el-input-number v-model="formData.version" :min="1" />
        </el-form-item>

        <el-collapse v-model="activeCollapseName" accordion>
          <el-collapse-item title="其他" name="1">
            <el-form-item label="排序">
              <el-input-number v-model="formData.sort" :min="1" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="formData.notes" type="textarea" />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="脚本" name="2">
            <el-form-item label="本地前置脚本" label-width="100px">
              <el-input v-model="formData.localCommand" type="textarea"
                placeholder="在当前环境执行，可用于执行打包命令如：npm run build" />
            </el-form-item>
            <el-form-item label="远程前置脚本" label-width="100px">
              <el-input v-model="formData.beforeScript" type="textarea" placeholder="在远程环境，文件上传前执行" />
            </el-form-item>
            <el-form-item label="远程后置脚本" label-width="100px">
              <el-input v-model="formData.afterScript" type="textarea" placeholder="在远程环境，文件上传后执行" />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { tipsWarning } from '@/utils/tips'
import { Edit, Delete, Search, CopyDocument } from '@element-plus/icons-vue'
import { open } from '@tauri-apps/plugin-dialog'
import { serversStore } from '@/utils/IndexDBWarp/index'
import { useCrudForm } from '@/hooks/useCrudForm'
import DeployHandle from './DeployHandle.vue'
import DownloadDirBtn from './DownloadDirBtn.vue'

const serverConfigs = ref([])
const activeCollapseName = ref([])

const formDataRef = ref(null)
const {
  tableData,
  dialogVisible,
  dialogTitle,
  formData,
  loading,
  handleAdd,
  handleCopy,
  handleEdit,
  handleDelete,
  submitForm,
} = useCrudForm({
  title: '项目信息',
  tableName: 'projectList',
  formInitData: {
    projectName: '',
    uploadType: 1,
    localPath: '',
    serve: '',
    remotePath: '',
    backupMethod: 1,
    version: 1,
    sort: 1,
    notes: '',
    localCommand: '',
    beforeScript: '',
    afterScript: ''
  },
  formRef: formDataRef
})
const formDataRules = reactive({
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  localPath: [{ required: true, message: '请输入路径', trigger: 'blur' }],
  serve: [{ required: true, message: '请选择服务器', trigger: 'change' }],
  remotePath: [{ required: true, message: '请输入远程路径', trigger: 'blur' }]
})

onMounted(() => {
  serversStore.getAll().then((res) => {
    serverConfigs.value = res || []
  })
})

const formatterServerData = (row) => {
  const serverConfig = serverConfigs.value.find((item) => item.id === row.serve)
  return serverConfig ? serverConfig.name : ''
}

const addProjectHandle = () => {
  if (!serverConfigs.value.length) {
    tipsWarning('请先添加服务器')
  } else {
    handleAdd()
  }
}

const selectFileHandle = async () => {
  if (formData.uploadType === 1) {
    // 选择gz压缩文件
    formData.localPath = await open({
      multiple: false,
      title: '请选择压缩文件',
      filters: [{ name: 'gz', extensions: ['gz'] }]
    })
  } else if (formData.uploadType === 2) {
    // 选择文件
    formData.localPath = await open({ multiple: false, title: '请选择文件' })
  } else {
    // 选择目录
    formData.localPath = await open({ multiple: false, title: '请选择部署目录', directory: true })
  }
}

const handleDownload = async (row) => {

}
</script>

<style scoped lang="scss"></style>
